<?php
namespace app\listen;

use think\facade\Db;
use app\event\AssetHistoriesEvent;


class InsertAssetHistoriesRecord
{
    public function handle(AssetHistoriesEvent $event)
    {
        //$db = Db::connect();
        //$db->startTrans();
        Db::startTrans();

        try {
            $assets = $event->assets;
            $instockId = $event->instockId;
            $userId = $event->userId;
            $companyId = $event->companyId;
            $type=$event->type;

            foreach ($assets as $asset) {
                $historyData = [
                    'AssetHistories_assets_id' => $asset['assets_id'],
                    'AssetHistories_type' => $type, // 或者根据需要动态设定
                    'AssetHistories_bill_id' => $instockId,
                    'AssetHistories_user_id' => $userId,
                    'AssetHistories_company_id' => $companyId,
                ];
                Db::table('AssetHistories')->insert($historyData);

            }

        // 如果所有插入都成功，则提交事务

            Db::commit();
        } catch (\Exception $e) {
       // 如果任何插入失败，则回滚事务

            Db::rollback();
            // 用log记录日志
            error_log('历史记录事假插入失败'.$e);
        // 这里可以根据项目需求抛出异常或记录日志等进一步处理
        }
    }
}